<script setup>
import { ref, computed } from "vue";
import {
  listPostService,
  deletePostService,
  postInfoService,
} from "@/api/postManage.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Delete } from "@element-plus/icons-vue";
import { userInfoService } from "@/api/user.js";
import { useUserInfoStore } from "@/stores/userInfo.js";

//获取用户信息
const userInfoStore = useUserInfoStore();
const getUserInfo = async () => {
  let result = await userInfoService();
  userInfoStore.setInfo(result.data);
};
getUserInfo();
// console.log(userInfoStore.info);

//帖子模块类型数据模型
const categorys = [
  { id: 1, name: "表白墙" },
  { id: 2, name: "跳蚤市场" },
  { id: 3, name: "招募" },
  // { id: 4, name: "找搭子" },
];

//帖子数据模型
const post = ref({
  postId: "",
  title: "",
  userId: "",
  categoryId: "",
  content: "",
  image: "",
  price: "",
  requirement: "", // 如果帖子类型为“招募”，则需要填写
  postTime: "",
  approvalStatus: "",
});

// 添加一个计算属性，将类别 ID 映射为中文名
const categoryNames = computed(() => {
  const mapping = {};
  categorys.forEach((category) => {
    mapping[category.id] = category.name;
  });
  return mapping;
});

//搜索数据模型
const categoryName = ref("");
const state = ref("");

// 响应式状态
const isShow = ref(false); // 是否显示帖子详情弹窗
const posts = ref([]); //帖子列表

//分页条数据模型
const pageNum = ref(1); //当前页
const total = ref(0); //总条数
const pageSize = ref(5); //每页条数
const onSizeChange = (size) => {
  pageSize.value = size;
  getPosts();
}; //修改每页条数
const onCurrentChange = (num) => {
  pageNum.value = num;
  getPosts();
}; //修改当前页

//显示中文状态
const getApprovalStatus = (status) => {
  if (status === 1) {
    return "待审核";
  } else if (status === 2) {
    return "已通过";
  } else if (status === 3) {
    return "未通过";
  } else {
    return "";
  }
};

//=======================================================================
//获取帖子列表数据
const postList = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    categoryName: categoryName.value ? categoryName.value : null,
    approvalStatus: state.value ? state.value : null,
    userId: userInfoStore.info.userId,
  };
  let result = await listPostService(params);
  total.value = result.data.total;
  posts.value = result.data.items;
};
postList();



//--------------------------------查看帖子详情---------------------------------
const postInfo = async (row) => {
  console.log(row.postId);
  let Data = {
    postId: row.postId,
  };
  let result = await postInfoService(Data);
  post.value = result.data;
  isShow.value = true;
  console.log(post.value);
};

//-------------------------------------删除帖子-------------------------
const deletePost =  (row) => {
  ElMessageBox.confirm("该帖子将被删除，你确定吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "提示",
  })
    .then(async () => {
      let result = await deletePostService(row.postId);
      ElMessage({
        type: "success",
        message: "已删除",
      });
      postList(); //刷新列表
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除取消",
      });
    });
};
</script>
 
 <!-- ================================================================================================== -->
<!-- **************************************************************************************************** -->
<!-- ================================================================================================== --> 

<template>
  <div>
    <!-- -----------------------------------搜索表单-------------------------------- -->
    <el-form inline>
      <el-form-item label="模块类别：">
        <el-select placeholder="请选择" v-model="categoryName">
          <el-option
            v-for="c in categorys"
            :key="c.id"
            :label="c.name"
            :value="c.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="状态：">
        <el-select placeholder="请选择" v-model="state">
          <el-option label="待审核" value="1"></el-option>
          <el-option label="已通过" value="2"></el-option>
          <el-option label="未通过" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="postList()">搜索</el-button>
        <el-button
          @click="
            categoryName = '';
            state = '';
          "
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!--------------------------------------帖子列表---------------------------------- -->
    <el-table :data="posts" style="width: 100%">
      <el-table-column
        label="帖子标题"
        width="200"
        prop="title"
      ></el-table-column>
      <el-table-column label="模块类别" prop="categoryId" width="200px">
        <template #default="{ row }">
          {{ categorys.find((item) => item.id === row.categoryId).name }}
        </template>
      </el-table-column>
      <el-table-column label="发表时间" prop="postTime"></el-table-column>
      <el-table-column label="状态" prop="approvalStatus">
        <template #default="{ row }">
          {{ getApprovalStatus(row.approvalStatus) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <!-- 操作 -->
        <template #default="{ row }">
          <el-button
            :icon="Search"
            circle
            plain
            type="primary"
            @click="postInfo(row)"
          ></el-button>
          <el-button
            :icon="Delete"
            circle
            plain
            type="danger"
            @click="deletePost(row)"
          ></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
    <!--------------------------------------帖子详情窗口---------------------------------- -->
    <el-dialog v-model="isShow" title="帖子详情" width="50%" center>
    <div v-show="isShow">
      <el-card class="box-card">
        <div v-html="post.title" style="zoom: 1.5;"></div>
        <p>作者：{{ post.username }}</p>
        <p>发布时间：{{ post.postTime }}</p>
        <p>内容：{{ post.content }}</p>
        <img :src="post.image" alt="post image" style="max-width: 100px; max-height: 100px;" />
        <p v-if="post.categoryId === 2">价格：{{ post.price }}</p>
        <p v-if="post.categoryId === 3">要求：{{ post.requirement }}</p>
        <p>审核状态：{{ getApprovalStatus(post.approvalStatus) }}</p>
      </el-card>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="isShow = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
  </div>
</template>

<!-- ================================================================================================== -->
<!-- **************************************************************************************************** -->
<!-- ================================================================================================== -->


<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>